<template>
    <div>
        <a-form :form="form" @submit="handleSubmit" @onValuesChange="onFormFieldsChange">
            <a-form-item v-bind="formItemLayout" label="是否新建客户">
                <a-switch v-model="newUserModel" @change="onUserModelChange"/>
            </a-form-item>
            <div v-if="newUserModel">
                <a-form-item v-bind="formItemLayout" label="购买者姓名">
                    <a-input v-decorator="buyerNameRule"/>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="联系电话1">
                    <a-input v-decorator="phone1Rule" type="phone"/>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="联系电话2">
                    <a-input v-decorator="phone2Rule" type="phone"/>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="使用者姓名">
                    <a-input v-decorator="userNameRule"/>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="使用者性别">
                    <a-select placeholder="请选择性别" v-decorator="sexRule">
                        <a-select-option value="男">男</a-select-option>
                        <a-select-option value="女">女</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="生辰">
                    <a-date-picker v-decorator="['birthday']" format="YYYY-MM-DD"></a-date-picker>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="亡辰（灵位专用）">
                    <a-date-picker v-decorator="['deathday']" format="YYYY-MM-DD"></a-date-picker>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="常用地址">
                    <a-input v-decorator="['address']"/>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="用户备注">
                    <a-input v-decorator="['userRemarks']"/>
                </a-form-item>
            </div>

            <a-form-item v-bind="formItemLayout" label="选择客户" v-if="!newUserModel">
                <a-auto-complete
                    v-decorator="userSelectorRule"
                    placeholder="请输入购买者姓名或者联系电话"
                    size="large"
                    style="width: 100%"
                    @select="onUserSelectorSelect"
                    @search="onUserSelectorSearch"
                >
                    <template slot="dataSource">
                        <a-select-option v-for="u in userSearchResult" :key="u.id">购买者：{{u.buyerName}}，电话：{{u.phone1}}</a-select-option>
                    </template>
                    <a-input>
                        <a-icon slot="suffix" type="search" class="certain-category-icon"/>
                    </a-input>
                </a-auto-complete>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="选择产品">
                <a-auto-complete
                    v-decorator="productSelectorRule"
                    placeholder="请输入商品编号或者商品名称"
                    size="large"
                    style="width: 100%"
                    @select="onProductSelectorSelect"
                    @search="onProductSelectorSearch"
                >
                    <template slot="dataSource">
                        <a-select-option v-for="u in productSearchResult" :key="u.id">编号：{{u.no}}，名称：{{u.title}}，价格：{{u.price}}元</a-select-option>
                    </template>
                    <a-input>
                        <a-icon slot="suffix" type="search" class="certain-category-icon"/>
                    </a-input>
                </a-auto-complete>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="订单状态">
                <a-select style="width: 130px" v-decorator="stateRule">
                    <a-select-option :value="1">未付款</a-select-option>
                    <a-select-option :value="2">已付款</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="付款方式" v-if="showPayType">
                <a-select style="width: 130px" v-decorator="payTypeRule">
                    <a-select-option value="现金">现金</a-select-option>
                    <a-select-option value="刷卡">刷卡</a-select-option>
                    <a-select-option value="支付宝">支付宝</a-select-option>
                    <a-select-option value="微信">微信</a-select-option>
                    <a-select-option value="其他">其他</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="订单备注">
                <a-input v-decorator="['remarks']" :disabled="!editModel"/>
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="附件">
                <a-button @click="selectOrderImages">
                    <a-icon type="upload"/>上传
                </a-button>
                <image-viewer
                    v-decorator="['reference', {
                    valuePropName: 'images'
                }]"
                    @deleteItem="onDeleteItem"
                    :canDelete="true"
                ></image-viewer>
            </a-form-item>
            <a-form-item v-bind="tailFormItemLayout">
                <a-button type="primary" html-type="submit">创建订单</a-button>
                <a-button @click="backHandler">返回</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>
<script>
import { Modal } from 'ant-design-vue';
import moment from 'moment';
import UserList from '@/views/users/userlist';
import { mapGetters } from 'vuex';
import _ from 'lodash';
import { Order } from '@/models/Order';
import ImageViewer from '@/components/imageviewer';
export default {
    data() {
        return {
            form: null,
            newUserModel: false,
            currentOrder: {},
            orderId: '',
            formItemLayout: {
                labelCol: {
                    span: 6
                },
                wrapperCol: {
                    span: 14
                }
            },
            tailFormItemLayout: {
                wrapperCol: {
                    xs: {
                        span: 24,
                        offset: 0
                    },
                    sm: {
                        span: 16,
                        offset: 8
                    }
                }
            },
            userSelectorRule: [
                'buyerName',
                {
                    rules: [{ required: true, message: '请选择一个购买者' }]
                }
            ],
            productSelectorRule: [
                'productdTitle',
                {
                    rules: [{ required: true, message: '请选择一个商品' }]
                }
            ],
            buyerNameRule: [
                'buyerName',
                {
                    rules: [{ required: true, message: '请输入购买者姓名' }]
                }
            ],
            userNameRule: ['userName'],
            sexRule: ['sex'],
            phone1Rule: [
                'phone1',
                {
                    rules: [
                        { required: true, message: '请输入联系电话' },
                        {
                            pattern: /^1(3|4|5|6|7|8)\d{9}$/,
                            message: '请输入正确的手机号码'
                        }
                    ]
                }
            ],
            phone2Rule: [
                'phone2',
                {
                    rules: [
                        {
                            pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/,
                            message: '请输入正确的电话号码'
                        }
                    ]
                }
            ],
            stateRule: [
                'state',
                {
                    initialValue: 1
                }
            ],
            payTypeRule: [
                'payType',
                {
                    initialValue: '现金'
                }
            ],
            userSearchResult: [],
            productSearchResult: [],
            currentSelectedUser: null,
            currentSelectedProduct: null,
            showPayType: false
        };
    },
    components: {
        [UserList.name]: UserList,
        [ImageViewer.name]: ImageViewer
    },
    created() {
        this.form = this.$form.createForm(this, {
            onFieldsChange: this.onFormFieldsChange
        });
        this.productId = this.$route.query.id;
        switch (this.$route.name) {
            case 'AddOrder':
                this.editModel = true;
                break;
            case 'ModifyOrder':
                this.editModel = true;
                this.modifyModel = true;
                break;
            case 'OrderDetail':
                this.editModel = false;
                break;
            default:
                this.editModel = false;
        }
    },
    methods: {
        handleSubmit(e) {
            e.preventDefault();
            this.form.validateFieldsAndScroll((err, values) => {
                if (!err) {
                    if (this.newUserModel) {
                        let uObj = {
                            buyerName: values.buyerName,
                            userName: values.userName,
                            sex: values.sex,
                            birthday: values.birthday,
                            deathday: values.deathday,
                            address: values.address,
                            phone1: values.phone1,
                            phone2: values.phone2,
                            remarks: values.userRemarks
                        };
                        this.$store.dispatch('addUser', uObj).then(added => {
                            this.currentSelectedUser = added;
                            let order = new Order({
                                state: values.state,
                                remarks: values.remarks,
                                isPayed: values.state === 2,
                                payType: values.payType,
                                reference: values.reference
                            });
                            order.setUser(added);
                            order.setProduct(this.currentSelectedProduct);
                            if (order.isPayed) {
                                order.setPresaleState(true);
                            }
                            this.$store.dispatch('addOrder', order).then(() => {
                                this.$success({
                                    title: '订单建立完成',
                                    onOk: () => {
                                        this.$router.replace({
                                            name: 'OrderDetail',
                                            query: {
                                                id: order.id
                                            }
                                        });
                                    }
                                });
                            });
                        });
                    } else {
                        let order = new Order({
                            state: values.state,
                            remarks: values.remarks,
                            isPayed: values.state === 2,
                            payType: values.payType,
                            reference: values.reference
                        });
                        this.$store
                            .dispatch(
                                'reduceStock',
                                this.currentSelectedProduct
                            )
                            .catch(reason => {
                                return;
                            });
                        order.setUser(this.currentSelectedUser);
                        order.setProduct(this.currentSelectedProduct);
                        if (order.isPayed) {
                            order.setPresaleState(true);
                        }
                        this.$store.dispatch('addOrder', order).then(() => {
                            this.$success({
                                title: '订单建立完成',
                                onOk: () => {
                                    this.$router.replace({
                                        name: 'OrderDetail',
                                        query: {
                                            id: order.id
                                        }
                                    });
                                }
                            });
                        });
                    }
                }
            });
        },
        onFormFieldsChange(props, fields) {
            if (fields.state) {
                if (fields.state.value === 2) {
                    this.showPayType = true;
                } else {
                    this.showPayType = false;
                }
            }
        },
        backHandler() {
            this.$router.go(-1);
        },
        modifyHandler() {
            this.editModel = true;
            this.modifyModel = true;
        },
        onUserSelectorSelect(value) {
            let user = _.find(this.users, { id: value });
            if (user) {
                this.currentSelectedUser = user;
            }
        },
        onUserSelectorSearch(value) {
            if (value === '') {
                return;
            }
            this.userSearchResult = _.filter(this.users, item => {
                return (
                    item.buyerName.includes(value) ||
                    item.phone1.includes(value)
                );
            });
        },
        onProductSelectorSelect(value) {
            let product = _.find(this.products, { id: value });
            if (product) {
                this.currentSelectedProduct = product;
            }
        },
        onProductSelectorSearch(value) {
            if (value === '') {
                return;
            }
            this.productSearchResult = _.filter(this.products, item => {
                return (
                    item.title.includes(value) ||
                    (item.no.includes(value) && item.state === 1)
                );
            });
        },
        onUserModelChange() {
            this.form = this.$form.createForm(this, {
                onFieldsChange: this.onFormFieldsChange
            });
        },
        selectOrderImages() {
            this.$store
                .dispatch('importImageToLocal')
                .then(result => {
                    let fixedImages = [];
                    if (result.length > 0) {
                        result.forEach(item => {
                            let s = _.replace(item, new RegExp(/\\/, 'g'), '/');
                            fixedImages.push('file://' + s);
                        });
                        this.form.setFieldsValue({
                            reference: fixedImages
                        });
                    }
                })
                .catch(reason => {
                    if (reason.message !== 'canceled') {
                        this.$error({ title: reason.message });
                    }
                });
        },
        onDeleteItem(item) {
            let fix1 = _.replace(item, 'file://', '');
            let fixedString = _.replace(fix1, new RegExp('/', 'g'), '\\');
            this.$store.dispatch('deleteImage', fixedString).then(() => {
                let arr = this.form.getFieldValue('reference');
                let index = _.findIndex(arr, a => {
                    return a === item;
                });
                arr.splice(index, 1);
                this.form.setFieldsValue({
                    reference: arr
                });
            });
        }
    },
    computed: {
        ...mapGetters(['users', 'products'])
    }
};
</script>
